const { app, BrowserWindow, Menu, dialog } = require("electron");

const path = require("path");

// 引入
const { getConfig, setConfig } = require("../utils/getAndSetConfig");

let createMainWindow = async () => {
  const windowStateKeeper = require("electron-window-state");
  let mainWindowState = windowStateKeeper({
    defaultWidth: 300,
    defaultHeight: 500,
    file: "mainWin.json",
  });
  // 窗口置顶
  let alwaysOnTop = true;
  if (app.isPackaged) {
    // 生产环境
    alwaysOnTop = false;
  } else {
    // 测试
    alwaysOnTop = true;
  }

  const win = new BrowserWindow({
    // ...winState.winOptions,
    x: mainWindowState.x,
    y: mainWindowState.y,
    width: mainWindowState.width,
    height: mainWindowState.height,

    width: 440,
    height: 700,

    // 窗口置顶
    alwaysOnTop,

    // 图标
    // icon: logo_window,
    // 创建时是否显示窗口
    show: false,
    webPreferences: {
      // 启用node
      // contextIsolation :true,
      // nodeIntegration: true,
      // contextIsolation: true,
      // 预加载
      preload: path.join(__dirname, "../preload/index.js"),
      nodeIntegration: true,
      webSecurity: false,

      nodeIntegrationInWorker: true
    },
  });

  // 右上角关闭
  win.on("close", (event) => {
    let exit = getConfig("exit");
    console.log("exit", exit);

    if (exit === true) {
      win.destroy();
      app.exit();
    } else if (exit !== undefined && exit === false) {
      event.preventDefault();
      win.setSkipTaskbar(true);
      win.minimize();
    } else if (exit === undefined) {
      let data = dialog.showMessageBoxSync(win, {
        type: "info",
        buttons: [
          "最小化到托盘",
          "直接退出",
          "以后都最小化到托盘",
          "以后都直接退出",
        ],
        title: "提示",
        message: "确定要退出吗？",
        detail: "以后可以到软件设置里面更改",
        defaultId: 0,
        cancelId: 1,
      });

      switch (data) {
        case 0:
          event.preventDefault();
          win.setSkipTaskbar(true);
          win.minimize();
          break;
        case 1:
          app.exit();

          break;
        case 2:
          setConfig("exit", false);
          event.preventDefault();
          win.setSkipTaskbar(true);
          win.minimize();
          break;
        case 3:
          setConfig("exit", true);
          app.exit();

          break;
        default:
          break;
      }
    }
  });

  // 软件是否最小化启动
  if (getConfig("start")) {
    win.setSkipTaskbar(true);
    win.minimize();
  } else {
    win.show();
  }



  if (app.isPackaged) {
    // 生产环境
    // null值取消顶部菜单栏
    Menu.setApplicationMenu(null);

    await win.loadURL(
      `file://${path.join(__dirname, "../../dist/index.html")}`
    );
  } else {
    // 测试环境
    await win.loadURL("http://localhost:5000");
  }
  mainWindowState.manage(win);
  return win;
};

module.exports = createMainWindow;
